<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML DOM - Paste as plain text</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="/css/demo.css" />
        <link rel="preconnect" href="https://fonts.gstatic.com" />
        <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Inter&family=Source+Code+Pro&display=swap"
        />
        <style>
            .container {
                align-items: center;
                display: flex;
                justify-content: center;
                padding: 2rem;
            }
            .editor {
                border: 1px solid #cbd5e0;
                height: 16rem;
                overflow: auto;
                width: 100%;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div contenteditable class="editor" id="editor"></div>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const editorEle = document.getElementById('editor');
                editorEle.addEventListener('paste', function (e) {
                    e.preventDefault();

                    // Get the copied text from the clipboard
                    const text = e.clipboardData
                        ? (e.originalEvent || e).clipboardData.getData('text/plain')
                        : // For IE
                        window.clipboardData
                        ? window.clipboardData.getData('Text')
                        : '';

                    if (document.queryCommandSupported('insertText')) {
                        document.execCommand('insertText', false, text);
                    } else {
                        // Insert text at the current position of caret
                        const range = document.getSelection().getRangeAt(0);
                        range.deleteContents();

                        const textNode = document.createTextNode(text);
                        range.insertNode(textNode);
                        range.selectNodeContents(textNode);
                        range.collapse(false);

                        const selection = window.getSelection();
                        selection.removeAllRanges();
                        selection.addRange(range);
                    }
                });
            });
        </script>
    </body>
</html>
